from django.http import HttpResponse
from django.shortcuts import render
import datetime
import json
from appOne.models import user


## 1. 跳转到页面
def demo1(request):
    return render(request, 'demo1.html')


## 2. 向页面返回数据
def demo2(request):
    context = {}
    context['hello'] = 'demo2'
    return render(request, 'demo2.html', context)


## 3. 向页面返回多种数据
def demo3(request):
    context = {}
    context['text'] = '1234567890'
    context['user'] = {'id': 1, 'name': '张三', 'sex': 3}
    context['list'] = ['AAA', 'BBB', 'CCC', 'DDD']
    context['pub_date'] = datetime.datetime.now()
    return render(request, 'demo3.html', context)


## 4. 响应ajax
def demo4(request):
    return render(request, 'demo4.html')


def demo4_ajax(request):
    return HttpResponse(json.dumps({'id': 1, 'name': '张三', 'sex': 3}),
                        content_type='application/json;charset=UTF-8')


## 5. 接受页面的传值
def demo5(request):
    return render(request, 'demo5.html')


def demo5_form(request):
    context = {}
    if request.method == "POST":
        name = request.POST.get("name", None)
        print(name)
        context["msg"] = "提交成功"
    else:
        context["msg"] = "提交失败"
    return render(request, 'demo5.html', context)


## 6.操作数据库
def demo6(request):
    user_list = user.objects.all()#查询所有
    context = {"user_list": user_list}
    return render(request, 'demo6.html', context)


def demo6_form(request):
    context = {}
    if request.method == "POST":
        name = request.POST.get("name", None)
        pwd = request.POST.get("pwd", None)
        birth = request.POST.get("birth", None)
        birth = datetime.datetime.strptime(birth, '%Y-%m-%d')
        # 向数据库插入数据
        user.objects.create(name=name, pwd=pwd, birth=birth)
        user_list = user.objects.all()
        context["msg"] = "提交成功"
        context["user_list"] = user_list
    else:
        context["msg"] = "提交失败"
    return render(request, 'demo6.html', context)